package com.gzsxy.lesson01.udp.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 多线程 upd 实现双发聊天功能
 */
public class TalkSend implements Runnable {

    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromIp;
    private String toIp;
    private int toPort;

    public TalkSend(int fromIp, String toIp, int toPort) {
        this.fromIp = fromIp;
        this.toIp = toIp;
        this.toPort = toPort;

        try {
            //设置发送端的端口
            socket = new DatagramSocket(fromIp);
            //准备数据： 控制台读取System.in   InputStreamReader获取控制台字符串输入流
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public TalkSend() {

    }

    @Override
    public void run() {


        while (true) {

            //readLine可以一次性获取全部的数据 ，这时BufferedReader特有的方法；
            // 传统必须要new char[1024]；  (len =reader.read(char) !=-1)
            //System.out.println(new String(char,0,len))输出

            String data = null;
            try {
                data = reader.readLine();
                byte[] datas = data.getBytes();
                //数据，数据的长度起始，要发送给谁
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,
                        new InetSocketAddress(this.toIp, this.toPort));

                //发送包
                socket.send(packet);
                if (data.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //关闭
        socket.close();
    }
}
